import time

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

url = "http://47.103.13.124:8001/iframe_out"

brower = webdriver.Chrome(executable_path='chromedriver')


def wait_element(brower, element_id, wait_time=10):
    try:
        WebDriverWait(brower, wait_time, 1).until(
            EC.presence_of_element_located((By.ID, element_id))
        )
    except Exception as e:
        raise Exception(e)

try:

    brower.get(url)
    brower.add_cookie({"name": "session",
                       "value": ".eJyrViotTi1SsqpWyiyOT0zJzcxTsjLQUcrJTwexSopKU3WUcvOTMnNSlayUDM3gQEkHrDE-M0XJyhjCzkvMBSmKKTVNMjMDkiamFkq1tQDfeR3n.YLOC4w.Xbnx1QbrvUh8OUPb5jauC_Aau9U"})
    brower.get(url)

    # 通过switch_to()方法将selenium的控制句柄转移到iframe中，从而可以获得iframe的HTML源码与控制权
    myframe = brower.find_element_by_id('myiframe')
    brower.switch_to.frame(myframe)

    email_input_id = 'inputEmail'
    wait_element(brower, email_input_id)
    email_input = brower.find_element_by_id(email_input_id)
    email_input.clear()
    email_input.send_keys('username')

    pwd_input_id = 'inputPassword'
    wait_element(brower, pwd_input_id)
    pwd_input = brower.find_element_by_id(pwd_input_id)
    pwd_input.clear()
    pwd_input.send_keys('123456')

    # 点击登录按钮
    button = brower.find_element_by_tag_name('div').find_element_by_tag_name('button')
    button.click()
finally:
    time.sleep(5)
    # 退出浏览器
    brower.close()
